<template>
  <div class="page-chargeSelect">

    <!-- 如果站点免费 -->
    <div v-bind:class="{'c-charge-free':unitprice==0}" class="c-header">
      <div class="c-num-box">
        <div class="c-num">{{num}}号</div>
        已选择插座
      </div>
      <div class="c-name">{{name}}</div>
       <div class="c-address">{{area}}{{address}}</div>

    </div>

    <!-- 如果站点不免费 -->
    <div v-if="unitprice!=0" class="c-tabs">
      <div v-if="deposit==0" class="c-tabs-box">
        <div class="c-tabs-header">
          <div @click="switchTabs(0)" class="c-item" v-bind:class="{ 'c-item-active':tabsNum==0 }">按时收费</div>
          <div @click="switchTabs(1)" class="c-item" v-bind:class="{ 'c-item-active':tabsNum!=0 }">按量收费</div>
        </div>
        <div class="c-tabs-body">
          <div v-bind:class="{ 'c-content-active':tabsNum==0 }"  class="c-content">
            <div class="c-list">
              <div v-for="(item,index) in hourList" v-bind:key="index" @click="switchHour(index)" v-bind:class="{'c-t-active':index==selectHour}"  class="c-t">{{item}}</div>
            </div>
            <div class="c-b-info">
              <p class="c-info-warning">
                提示：大功率电瓶车按时收费可能会被拒充，建议使用按量收费
              </p>
              <p class="c-info-normal">
                提示：如发生过载引起意外中断、电池充满充电时间未到、插头被别人拔出等情况，充电剩余金额不予退还。
              </p>
            </div>
          </div>
          <div v-bind:class="{ 'c-content-active':tabsNum!=0 }" class="c-content">
            <div class="c-list">
              <div class="c-t c-t-active">1小时/{{(unitprice/100).toFixed(2)}}元</div>
            </div>
            <div class="c-b-info">
            <!-- <h4>收费标准(按量收费)</h4> -->
            <!--
            <ul class="c-info-list">
              <li>
                <p>0~100瓦</p>
                <span>0.15元/小时</span>
              </li>
              <li>
                <p>0~100瓦</p>
                <span>0.15元/小时</span>
              </li>
              <li>
                <p>0~100瓦</p>
                <span>0.15元/小时</span>
              </li>
              <li>
                <p>0~100瓦</p>
                <span>0.15元/小时</span>
              </li>
            </ul>
            -->
            <p>提示：插座意外断开，将返还剩余金额</p>
            </div>
          </div>
        </div>
      </div>
      <div v-else class="c-tabs-box">
        <div class="c-tabs-header">
          <div class="c-item-header">按量收费</div>
        </div>
        <div class="c-tabs-body">
          <div class="c-content c-content-money">
            <div class="c-list">
              <div class="c-t c-t-active">1小时/{{(unitprice/100).toFixed(2)}}元</div>
            </div>
            <div class="c-b-info">
            <p>提示：插座意外断开，将返还剩余金额</p>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 按钮 -->
    <div class="page-bottom">
      <div @click="charge" v-if="unitprice==0" class="btn">免费充电</div>
      <div @click="charge" v-else class="btn">开始充电</div>
    </div>

  </div>
</template>


<script>
import Interface from "../GlobalData";
import { MessageBox } from "mint-ui";
export default {
  name: "ChargeSelect",
  data() {
    return {
      id: "",
      num: "",
      name: "",
      deposit: 0,
      area: "",
      address: "",
      lat: 0,
      lon: 0,
      unitprice: 252,
      tabsNum: 0,
      payMoney: 100,

      selectHour: 0,
      hourList: ["1元4小时", "2元8小时", "3元充满"],
      payType: "weixin" // weixin , account
    };
  },
  mounted() {},
  created() {
    var self = this;
    var id = self.$route.query.id;
    var num = self.$route.query.num;
    self.id = id;
    self.num = num;
    if (self.id != undefined) {
      // 初始化充电站信息
      self.init(id, function() {
        // 初始化当前用户信息
        self.initUser();
      });
    }
  },
  methods: {
    init(id, callback) {
      //更新（获取设备信息）
      var self = this;

      // 定义请求
      var req = this.Axios.get(this.Interface.host, {
        params: self.GetQuerys({ id: id })
      });

      // 请求成功
      req.then(res => {
        var data = res.data.data;
        var site = data.plug.site;
        self.name = site.name;
        self.address = site.address;
        self.area = site.area;
        self.unitprice = site.unitPrice;
        if (site.unitPrice == 0) {
          self.payMoney = 0;
        }

        if (callback) callback();
      });
    },
    initUser() {
      //更新（获取设备信息）
      var self = this;
      // 定义请求
      var req = this.Axios.get(this.Interface.host, {
        params: self.GetMeQuerys()
      });

      // 请求成功
      req.then(res => {
        var data = res.data.data.me;
        // 测试赋值数据
        if (data != null) {
          self.deposit = data.deposit;

          // 蛋疼的判断
          if (data.deposit != 0 && self.unitprice != 0) {
            self.tabsNum = 1;
          }
        }
      });
    },
    GetQuerys({ id }) {
      return {
        query: `{
                plug(id:${id}) {
                  id
                  code
                  number
                  sn
                  state
                  countDown
                  site{
                    name
                    id
                    area
                    address
                    unitPrice
                  }
                }
              }`
      };
    },
    GetMeQuerys() {
      return {
        query: `{
                me {
                  deposit
                }
              }`
      };
    },
    switchTabs(index) {
      this.tabsNum = index;
      console.log(index);
    },
    PaySwitch(types) {
      this.payType = types;
    },
    switchHour(index) {
      this.selectHour = index;
      this.payMoney = [100, 200, 300][index];
    },
    CreateOrder() {
      var self = this;

      var plugId = this.id;
      var orderPrice = this.payMoney;
      var obj = {
        plugId: plugId,
        price: orderPrice
      };

      // 请求内容
      var req = this.Axios.post(this.Interface.CreateOrder, obj);

      // 返回结果
      req.then(res => {
        var data = res.data;

        if (data.ok) {
          var result = data.data;
          var OrderData = result.order;

          if (result.config != undefined) {
            // 调用微信支付
            let config = result.config;
            wx.ready(function() {
              wx.chooseWXPay({
                timestamp: config.timestamp, // 支付签名时间戳，注意微信jssdk中的所有使用timestamp字段均为小写。但最新版的支付后台生成签名使用的timeStamp字段名需大写其中的S字符
                nonceStr: config.nonceStr, // 支付签名随机串，不长于 32 位
                package: config.package, // 统一支付接口返回的prepay_id参数值，提交格式如：prepay_id=***）
                signType: config.signType, // 签名方式，默认为'SHA1'，使用新版支付需传入'MD5'
                paySign: config.paySign, // 支付签名
                success: function(res) {
                  // 支付成功后的回调函数
                  if (res.errMsg == "chooseWXPay:ok") {
                    self.$router.push({
                      path: "chargeDetails",
                      query: { id: OrderData.id }
                    });
                    self.Toast("付款成功");
                  }
                }
              });
            });
          } else {
            // 免费的 或者 已经充值过有余额的
            self.$router.push({
              path: "chargeDetails",
              query: { id: OrderData.id }
            });
          }
        } else {
          this.Toast.show(data.msg);
        }
      });
    },
    charge() {
      var self = this;

      // 判断是否免费
      if (self.unitprice != 0) {
        // 判断收费模式
        if (self.tabsNum > 0) {
          // 判断余额是否还有
          if (self.deposit != 0) {
            // 直接创建订单
            self.payMoney = 0;

            // self.CreateOrder();

            MessageBox.confirm(`请确保您的插头已插入?`, "提示")
              .then(action => {
                if (action == "confirm") {
                  self.CreateOrder();
                }
              })
              .catch(err => {
                if (err == "cancel") {
                  console.log("123");
                }
              });
          } else {
            // 先去充值了
            MessageBox({
              title: "提示",
              message: "按量收费模式需要充值后使用，您账户当前为0，是否要去充值?",
              showCancelButton: true,
              confirmButtonText: "充值"
            })
              .then(action => {
                if (action == "confirm") {
                  var url = encodeURI(window.location.href);
                  this.$router.push({
                    path: "recharge",
                    query: { url: url }
                  });
                } else {
                  console.log("您不去充值了");
                }
              })
              .catch(err => {
                if (err == "cancel") {
                  console.log("123");
                }
              });
          }
        } else {
          // 按小时收费-------去创建订单
          MessageBox.confirm(`请确保您的插头已插入?`, "提示")
            .then(action => {
              if (action == "confirm") {
                self.CreateOrder();
              }
            })
            .catch(err => {
              if (err == "cancel") {
                console.log("123");
              }
            });
          // self.CreateOrder();
        }
      } else {
        // 免费去充电，充电前提示注意信息
        MessageBox.confirm(`请确保您的插头已插入?`, "提示")
          .then(action => {
            if (action == "confirm") {
              self.CreateOrder();
            }
          })
          .catch(err => {
            if (err == "cancel") {
              console.log("123");
            }
          });
      }
    }
  }
};
</script>



<style lang="less" scoped>
.page-chargeSelect {
  position: relative;
  width: 100%;
  height: 100%;
  background: #f5f5f5;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  box-sizing: border-box;
  padding-bottom: 120px;
}

// 头部
.c-header {
  position: relative;
  background: #fff;
  margin-bottom: 30px;
  border-bottom: 1px solid #ececec;
  box-sizing: border-box;
  padding: 30px 210px 30px 30px;
  min-height: 180px;
  &.c-charge-free {
    position: relative;

    &:after {
      position: absolute;
      left: 0;
      top: 0;
      width: 128px;
      height: 128px;
      background: url("../public/imgs/icon-free.png") 0 0 no-repeat;
      background-size: 100px 100px;
      content: "";
      display: none;
    }
  }

  .c-num-box {
    position: absolute;
    width: 180px;
    right: 30px;
    top: 30px;
    font-size: 28px;
    height: 110px;
    border: 2px solid #2992ed;
    color: #2992ed;
    border-radius: 10px;
    text-align: center;

    .c-num {
      width: 180px;
      height: 65px;
      line-height: 65px;

      display: -webkit-box;
      -webkit-box-pack: center;
      -webkit-box-align: center;
      font-size: 36px;
    }
  }

  .c-name {
    font-size: 32px;
    height: 40px;
  }
  .c-address {
    line-height: 40px;
    color: #999;
    padding-left: 40px;
    padding: 0 40px 0 25px;
    background: url("../public/imgs/icon-a.png") -5px 5px no-repeat;
    background-size: 32px 32px;
    font-size: 24px;
  }
}

// 选项卡
.c-tabs {
  background: #fff;
  margin-bottom: 30px;
  -webkit-box-flex: 1;

  .c-tabs-header {
    width: 100%;
    height: 80px;
    line-height: 90px;
    display: -webkit-box;

    .c-item {
      position: relative;
      display: -webkit-box;
      -webkit-box-flex: 1;
      -webkit-box-pack: center;
      -webkit-box-align: center;
      font-size: 28px;
    }

    .c-item-active {
      color: #2992ed;
      &:after {
        position: absolute;
        width: 120px;
        height: 3px;
        background: #2992ed;
        left: 50%;
        bottom: 0;
        transform: translate(-50%, 0);
        content: "";
      }
    }

    .c-item-header {
      box-sizing: border-box;
      font-size: 28px;
      -webkit-box-flex: 1;
      border-bottom: 1px solid #ececec;
      margin: 0 30px;
      height: 80px;
      line-height: 80px;
    }
  }
}

.c-tabs-body {
  box-sizing: border-box;
  padding: 20px 30px 50px;

  .c-content {
    display: none;
  }
  .c-content-money {
    display: block;
  }
  .c-content-active {
    display: block;
  }
}

.c-list {
  width: 100%;
  overflow: hidden;
  box-sizing: border-box;
  padding: 10px 0;
  margin-bottom: 30px;
  div {
    float: left;
    width: 28%;
    margin-right: 5.3%;
    height: 70px;
    font-size: 22px;
    text-align: center;
    -webkit-border-radius: 10px;
    display: -webkit-box;
    -webkit-box-align: center;
    -webkit-box-pack: center;
    border: 2px solid #2992ed;

    &:nth-child(3n) {
      margin-right: 0;
    }
  }
  .c-t-active {
    border-color: #2992ed;
    background: #2992ed;
    color: #fff;
  }
}

.c-info-warning {
  font-size: 30px;
  color: #f00;
  line-height: 35px;
  margin: 20px 0;
}

.c-info-normal {
  line-height: 35px;
}
.c-b-info h4 {
  font-size: 28px;
  height: 50px;
}
.c-info-list {
  width: 100%;
  overflow: hidden;
  display: -webkit-box;
  margin-bottom: 50px;
}
.c-info-list li {
  -webkit-box-flex: 1;
  height: 80px;
  display: -webkit-box;
  -webkit-box-pack: center;
  -webkit-box-orient: vertical;
  -webkit-box-align: center;
  text-align: center;
  line-height: 40px;
}
.c-info-list li:nth-child(4n) {
  margin-right: 0;
}

/* 免费 */
.c-container {
  display: -webkit-box;
  -webkit-box-align: start;
  -webkit-box-pack: center;
  box-sizing: border-box;
  padding: 50px 0;
  .c-body {
    font-size: 40px;
    height: 100px;
    line-height: 100px;
    // background: url("../public/imgs/icon-free.png") 0 center no-repeat;
    // background-size: 80px 80px;
    box-sizing: border-box;
    color: #00ac64;
  }
}

// 底部按钮
.page-bottom {
  height: 120px;
  box-sizing: border-box;
  width: 100%;
  padding: 20px 100px;
  .btn {
    text-align: center;
    background: #2992ed;
    color: #fff;
    font-size: 28px;
    width: 100%;
    height: 100%;
    border-radius: 40px;
    line-height: 80px;
  }
}
</style>
